local blaze = require "blaze"
local game = require "club.threecard.baccarat"
local consts = game.util.consts

local log = blaze.logging.get("bet_summarizing")

local M = game.ui.element()

M.store_watchers = {
    gameplay = {
        ["$"] = function(self, store, state)
            self:reset()
        end,

        ["玩家下注"] = function(self, store, state, args)
            local area_id = args.area_id
            local amount = args.amount
            local player = args.player
            self:bet(player, area_id, amount)
        end,

        ["阶段变更"] = function(self, store, state, args)
            if state.phase_id == consts.PHASE_PAYOUT then
                self:reset()
            end
        end,

        ["恢复游戏场景"] = function(self, store, state, args)
            self:reset()
        end,        
    }
}

function M:ctor()
    self.res = "club.threecard.baccarat/ui/ingame.b:bet_summarizing"
    self.areas = {}
    self.values = { 0, 0, 0, 0, 0}
    self.self_values = { 0, 0, 0, 0, 0}
    self.self_areas = {}
end

function M:on_injected()
    self.areas[1] = self.area_1_txt
    self.areas[2] = self.area_2_txt
    self.areas[3] = self.area_3_txt
    self.areas[4] = self.area_4_txt
    self.areas[5] = self.area_5_txt

    self.self_areas[1] = self.area_1_self_txt
    self.self_areas[2] = self.area_2_self_txt
    self.self_areas[3] = self.area_3_self_txt
    self.self_areas[4] = self.area_4_self_txt
    self.self_areas[5] = self.area_5_self_txt
end

function M:reset()
    self.values[1] = 0
    self.values[2] = 0
    self.values[3] = 0
    self.values[4] = 0
    self.values[5] = 0

    self.self_values[1] = 0
    self.self_values[2] = 0
    self.self_values[3] = 0
    self.self_values[4] = 0
    self.self_values[5] = 0
    self:lazy("on_reset")
end

function M:on_reset()
    self.areas[1].text = ""
    self.areas[2].text = ""
    self.areas[3].text = ""
    self.areas[4].text = ""
    self.areas[5].text = ""

    self.self_areas[1].text = ""
    self.self_areas[2].text = ""
    self.self_areas[3].text = ""
    self.self_areas[4].text = ""
    self.self_areas[5].text = ""
end

function M:bet(player, area_id, amount)
    if not self.areas[area_id] then
        log.error("没有area_id:" .. tostring(area_id))
        return
    end

    self.values[area_id] = self.values[area_id] + amount
    self.areas[area_id].text = game.i18n.number(self.values[area_id], "chip5")

    if game.kbe.player() and game.kbe.player() == player then
        self.self_values[area_id] = self.self_values[area_id] + amount
        self.self_areas[area_id].text = game.i18n.number(self.self_values[area_id], "chip5")
    end
end

return M